#!/usr/bin/env python3


# 合并表格时，需要把很多表格的内容复制到一个表格中，这个脚本就是用来实现这个功能的
#

import argparse
import sys


sys.path.append("../lib")
from inner_util import prepare_dir, get_files
from spread_sheet import Spreadsheet
import datetime
import os

TARGET_DIR = "dist"


def parse_args():
    parser = argparse.ArgumentParser(description="汇总表格")
    parser.add_argument("--start-row", type=int, help="起始行号，0索引")
    parser.add_argument("--data", help="数据文件目录")
    parser.add_argument("template", help="文件路径")
    return parser.parse_args()


def usage():
    print("""
python3 merge.py --start-row=<0索引行号> --data=<data_dir> template.xlsx
""")


def copy_row_style_with_height(ws, source_row, target_row):
    """
    完整复制行样式，包括行高和对应列的列宽
    此处行号是1索引的

    参数:
    ws: 工作表对象
    source_row: 源行号(整数)
    target_row: 目标行号(整数)
    """
    # 复制行高
    if source_row in ws.row_dimensions:
        ws.row_dimensions[target_row].height = ws.row_dimensions[source_row].height

    # 获取源行和目标行的行对象
    source = ws[source_row]
    target = ws[target_row]

    # 遍历源行的每个单元格
    for idx, source_cell in enumerate(source):
        # 获取目标行的对应单元格
        target_cell = target[idx]

        # 复制列宽（只复制一次，避免重复操作）
        if idx == 0:  # 只需处理一次列宽
            col_letter = source_cell.column_letter
            if col_letter in ws.column_dimensions:
                ws.column_dimensions[col_letter].width = ws.column_dimensions[
                    col_letter
                ].width

        # 复制所有样式属性
        if source_cell.has_style:
            # 直接复制整个样式对象（更高效）
            target_cell._style = source_cell._style

            # 如果需要单独复制各个样式属性（更精确控制）
            """
            target_cell.font = Font(**dict(source_cell.font))
            target_cell.fill = PatternFill(**dict(source_cell.fill))
            target_cell.border = Border(**dict(source_cell.border))
            target_cell.alignment = Alignment(**dict(source_cell.alignment))
            target_cell.number_format = source_cell.number_format
            target_cell.protection = Protection(**dict(source_cell.protection))
            """


def main():
    usage()

    prepare_dir(TARGET_DIR, False)

    args = parse_args()

    print("Args", args)

    main = Spreadsheet(args.template)

    data_files = get_files(args.data, ".xlsx", True)

    for data_file in data_files:
        print(f"合并 {data_file} 到原表")
        data_spread_sheet = Spreadsheet(data_file)
        main.merge(data_spread_sheet, args.start_row)

    timestamp = datetime.datetime.now()
    timestr = timestamp.strftime("%Y%m%d%H%M%S")

    target_name = os.path.splitext(args.template)[0]
    target_path = os.path.join(
        TARGET_DIR, f"合并_{timestr}_{os.path.basename(target_name)}.xlsx"
    )
    print("Target", target_path)

    for i in range(10, main.ws.max_row):
        copy_row_style_with_height(main.ws, args.start_row + 1, i)

    # main.ws["A3"] = (
    #     "州（市）：玉溪市                                        填报人：赵鹏                           联系方式：18287790135"
    # )
    main.save_as(target_path)

    print("Done")


if __name__ == "__main__":
    main()
